﻿#region Using Statements
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;


#endregion
public class Proect : HaveToByte
{
    public  const string ext = ".proect";
    string fullfilename { get { return Environment.CurrentDirectory + "\\" + name + ext; } }

    public string name { get; set; }
    public string home { get; set; }
    public List<Zapros> zaproses = new List<Zapros>();
    public List<Rezult> rezults = new List<Rezult>();
    Client form;
    public Proect() //Пустой проект для редактора
    { }
    public Proect (Client _form, string _name) //Загрузка из файла
    {
        form = _form;
        name = _name;
        if (File.Exists(_name))
        {
            try
            {
                byte[] b = File.ReadAllBytes(_name);
                using (MemoryStream ms = new MemoryStream(b))
                using (BinaryReader br = new BinaryReader(ms))
                {
                    name = BYTE.ToShortString(br);
                    home = BYTE.ToShortString(br);
                    int count = br.ReadInt32();
                    for (int i = 0; i < count; i++)
                    {
                        zaproses.Add(new Zapros(br));
                    }
                    for (int i = 0; i < br.ReadInt32(); i++)
                    {
                        rezults.Add(new Rezult(br));
                    }
                }
            }
            catch (Exception e)
            {
                form.New_Proect();
            }
        }
    
    }
    public string get_zapros()
    {
        StringBuilder rez = new StringBuilder();
        foreach (Zapros z in this.zaproses)
	    {
    		 rez.Append(z.slovo+"\r\n");
	    }
        return rez.ToString();
    }
   
    public byte[] ToByte()
    {
        List<byte> b = new List<byte>();
        b.AddRange(ToBYTE.ShortString(name));
        b.AddRange(ToBYTE.ShortString(home));

        b.AddRange(BitConverter.GetBytes(zaproses.Count));
        foreach(Zapros z in zaproses)
                b.AddRange(z.ToByte());

        b.AddRange(BitConverter.GetBytes(rezults.Count));
        foreach (Rezult r in rezults)
            b.AddRange(r.ToByte());

        return b.ToArray();
    }
   
    public override string ToString()
    {
        return this.name + "["+zaproses.Count+"] : " + this.home;
    }
    public void Save()
    {
        using (FileStream stream = File.Open(fullfilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
        {
            byte[] b = ToByte();
            stream.Write(b, 0, b.Length);
        }
    }
}
